<?php


class VerificationController extends BaseController
{
    public static function getVerification(){
        $rand_num = rand();        //生成随机数
        $str = md5($rand_num);  //取得该数md5值

        $num_code = 4;        //验证码字符数
        $str_code = substr($str, 0, $num_code);     //从md5截取字符串作为验证码

        $width = 120;        //验证码图片宽度
        $height = 55;        //高度
        $img = imagecreate($width, $height);    //创建图像句柄

        $bg_color = imagecolorallocate($img, 255, 255, 255);      //背景色
        $border_color = imagecolorallocate($img, 0, 0, 0);        //前景色
        imagerectangle($img, 0, 0, $width-1, $height-1, $border_color);    //绘制边框

        $font_file=realpath("./arial.ttf");
        //随机字体颜色
        for ($i=0; $i < $num_code; $i++) {
            # code...
            $str_color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255));
            $font_size = 17;
            $str_x = floor( ($width / ($num_code + 1)) * $i ) + rand(7,20);
            $str_y = rand( 20,$height - 10 );
            imagettftext($img,$font_size,rand(-45,45),$str_x,$str_y,$str_color,$font_file,$str_code[$i]);

        }

        //绘制随机干扰点颜色
        $num_disturb_points = 200;
        for ($i=0; $i < $num_disturb_points; $i++) {
            # code...
            $point_color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255));
            $point_x = rand(2,$width - 2);
            $point_y = rand(2,$height - 2);
            imagesetpixel($img, $point_x, $point_y, $point_color);

        }

        //绘制随机颜色直线
        $line = 5;
        for ($i=0; $i < $line; $i++) {
            # code...
            $line_color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255));
            $line_x1 = rand(2,$width - 2);
            $line_y1 = rand(2,$height - 2);
            $line_x2 = rand(2,$width - 2);
            $line_y2 = rand(2,$height - 2);
            imageline($img, $line_x1, $line_y1, $line_x2, $line_y2, $line_color);
        }


        $_SESSION['verificationCode']=$str_code;
        header("Content-type: image/png");        //发送header信息
        imagepng($img);            //输出图像
        imagedestroy($img);        //释放与图像关联内存
    }

    public static function checkVerification($verificationCode){
        if(isset($_SESSION['verificationCode'])) {
            if (strcasecmp($_SESSION['verificationCode'], $verificationCode)==0) {
                return true;
            }
        }
        return false;
    }
}